<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\lib\SuPengJun;
use app\api\service\CircleService;
use app\api\service\DynamicService;
use app\api\service\GoodsService;
use app\common\model\activity\ActivityModel;
use app\common\model\BannerModel;
use app\common\model\circle\CircleModel;
use app\common\model\ClauseModel;
use app\common\model\dynamic\DynamicModel;
use app\common\model\goods\GoodsCardModel;
use app\common\model\goods\GoodsModel;
use app\common\model\goods\GoodsProductModel;
use app\common\model\order\OrderModel;
use app\common\model\user\UserCartModel;
use app\common\model\user\UserFollowModel;
use app\common\model\user\UserModel;
use app\common\service\ConfigService;
use app\common\model\system\PluginModel;
use plugin\activity\controller\api\Activity;
use think\facade\Db;
use think\Request;
use think\response\Json;

class Index extends Controller
{
    protected array $middleware = [
        'api' => ['except' => ['init_config', 'banner', 'test','index']],
        'orCheck' => ['only' => ['init_config', 'banner', 'test']]
    ];

    public function index() : Json
    {
//        return json_encode([
//            'code' => 1,
//            'msg' => 'success',
//        ]);
        return json([
            'code' => 122213213123,
            'msg' => 'success',
        ]);
    }


    public function test(Request $request)
    {
        return success('success', $data ?? []);
    }

    /**
     * 初始化小程序应用配置
     */
    public function init_config(Request $request)
    {
        $where[] = ['status', '=', 1];
        $data['live'] = PluginModel::where('name', 'liveStreaming')->where($where)->value('id') ? true : false;
        $data['card'] = PluginModel::where('name', 'goodsCard')->where($where)->value('id') ? true : false;
        $data['activity'] = PluginModel::where('name', 'activity')->where($where)->value('id') ? true : false;
        $data['waterfall'] = PluginModel::where('name', 'waterfall')->where($where)->value('id') ? true : false;
        $data['classify'] = PluginModel::where('name', 'goodsClassify')->where($where)->value('id') ? true : false;
        $data['note_shop'] = PluginModel::where('name', 'noteShop')->where($where)->value('id') ? true : false;
        $data['note_video'] = PluginModel::where('name', 'noteVideo')->where($where)->value('id') ? true : false;
        $data['app_xcx'] = ConfigService::get('applet', 'app_xcx');
        $data['app_bq'] = ConfigService::get('applet', 'app_bq');
        $data['upload_type'] = ConfigService::get('system', 'upload_type');
        if ($data['app_xcx']) $data['app_xcx'] = explode(',', $data['app_xcx']);
        if ($data['app_bq']) $data['app_bq'] = explode(',', $data['app_bq']);
        event('InitConfig', ['a' => 1, 'b' => 2, 'c' => 'xinxuan']);
        return success('success', $data);
    }

    public function banner(Request $request)
    {
        $uid = $request->uid;
        $condition[] = ['status', '=', 1];
        $data['banner'] = BannerModel::where($condition)->field('id,cover,type,type_id,type_url')
            ->order(['weigh' => 'desc', 'id' => 'desc'])->select();
        $condition[] = ['user_id', '=', $uid];
        $data['is_order'] = OrderModel::where($condition)->where('type', 0)->value('id') > 0;
        $data['cart_count'] = UserCartModel::where($condition)->count();
        $ids = GoodsCardModel::alias('c')
            ->join('spj_user_card uc', 'c.id = uc.card_id')
            ->where('uc.user_id', $uid)
            ->group('c.id, c.quantity')
            ->having('COUNT(uc.card_id) >= c.quantity')
            ->column('c.id');
        $data['is_card'] = GoodsCardModel::where('id', 'not in', $ids)
            ->where('type', 1)->where('status', 1)->count() > 0 ? true : false;
        return success('success', $data);
    }

    public function search(Request $request)
    {
        $uid = $request->uid;
        $kw = $request->get('kw', '');
        $type = $request->get('type', '');
        if ($type == 0) {
            $condition[] = ['content|adds_name|circle_name|activity_name', 'like', '%' . $kw . '%'];
            $condition[] = ['status', 'in', [2, 3]];
            $order = ['top' => 'desc', 'id' => 'desc', 'browse' => 'desc'];
            $data = DynamicModel::where($condition)->order($order)
                ->field(DynamicService::dynamic_find())
                ->paginate(8);
            $data = DynamicService::dynamic_map($data, $uid, 1);
            DynamicModel::whereIn('id', $data->column('id'))->update(['browse' => Db::raw('browse+1')]);
        } else if ($type == 1) {
            $condition[] = ['tags|name|intro|details', 'like', '%' . $kw . '%'];
            $condition[] = ['status', '=', 1];
            $data = GoodsModel::where($condition)
                ->field(GoodsService::goods_find())
                ->order(['weigh' => 'desc', 'id' => 'desc'])
                ->paginate(12);
            $data->map(function ($v) {
                $v['browse'] = SuPengJun::convert($v['browse']);
                $v['product'] = GoodsProductModel::where('goods_id', $v['id'])->where('status', 1)
                    ->order(['weigh' => 'desc', 'id' => 'desc', 'stock' => 'desc'])
                    ->field('price,line_price')->find();
                $v['product']['line_price'] = SuPengJun::formatPrice($v['product']['line_price']);
                return $v;
            });
        } else if ($type == 2) {
            $condition[] = ['name|intro', 'like', '%' . $kw . '%'];
            $condition[] = ['status', 'in', [1, 2]];
            $data = CircleModel::where($condition)
                ->field('id,name,avatar,intro,browse')
                ->order(['weigh' => 'desc', 'id' => 'desc'])
                ->paginate(12);
            $data = CircleService::circle_map($data);
        } else if ($type == 3) {
            $condition[] = ['u.name|u.intro', 'like', '%' . $kw . '%'];
            $condition[] = ['status', '=', 1];
            $data = UserModel::where($condition)
                ->alias('u')
                ->join('spj_user_privacy up', 'u.id = up.user_id')
                ->where('up.search', 1)
                ->field('u.id,u.name,u.avatar,u.gender,u.age,u.country,u.province,u.city')
                ->paginate(18);
            $data->map(function ($v) {
                if (!$v['province']) $v['province'] = $v['city'];
                if (!$v['province']) $v['province'] = $v['country'];
                $v['dynamic'] = DynamicModel::where('user_id', $v['id'])->count();
                $v['fans'] = UserFollowModel::where('follow_id', $v['id'])->count();
                return $v;
            });
        } else if ($type == 'activity') {
            $condition[] = ['name|intro|adds_name', 'like', '%' . $kw . '%'];
            $condition[] = ['status', '<>', 4];
            $field = 'id,imgs,name,start_time,end_time,adds_name,browse,status';
            $data = ActivityModel::where($condition)->field($field)
                ->order(['weigh' => 'desc', 'status' => 'asc', 'id' => 'desc'])
                ->paginate(12);
            $data->map(function ($v) use ($uid) {
                return Activity::attr($v, $uid);
            });
        }
        return success('success', $data ?? ['data' => []]);
    }

    public function clause(Request $request)
    {
        $id = $request->get('id');
        $data = ClauseModel::where('id', $id)->where('status', 1)->value('content');
        return success('success', $data);
    }
}
